package org.jmh.gift.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.jmh.gift.client.OrderClient;
import org.jmh.gift.domain.AccountAlipay;
import org.jmh.gift.domain.OrderGift;
import org.jmh.gift.domain.PayOrder;
import org.jmh.gift.dto.PcWebPayDTO;
import org.jmh.gift.mapper.PayOrderMapper;
import org.jmh.gift.service.IAccountAlipayService;
import org.jmh.gift.service.IPayOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.jmh.gift.util.AjaxResult;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lingfeng
 * @since 2024-08-06
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IAccountAlipayService accountAlipayService;
    @Autowired
    private OrderClient orderClient;
    @Override
    public void cancel(String uniPayOrderSn) {
        //修改订单状态
        payOrderMapper.updateByStatus(-1,uniPayOrderSn);
        PayOrder payOrder = super.selectOne(new EntityWrapper<PayOrder>().eq("uni_pay_order_sn", uniPayOrderSn));
        if(1 == payOrder.getPayType()){
            //设置取消接口对象
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", uniPayOrderSn);
            request.setBizContent(bizContent.toString());
        }
    }

    @Override
    public PayOrder createPayOrder(PcWebPayDTO dto) {
        RLock lock = redissonClient.getLock(dto.getUniPayOrderSn());
        try {
            lock.lock();
            PayOrder payOrder = super.selectOne(
                    new EntityWrapper<PayOrder>().eq("uni_pay_order_sn", dto.getUniPayOrderSn()));
            if(Objects.nonNull(payOrder)){
                return payOrder;
            }
            payOrder = new PayOrder();
            payOrder.setCreateTime(new Date());
            AjaxResult ajaxResult = orderClient.getOrderByParentOrderNo(dto.getParentOrderNo());
            if(!ajaxResult.getSuccess()){
                throw new RuntimeException("支付单weichuangjianchenggong");
            }
            String s1 = JSONObject.toJSONString(ajaxResult.getData());
            List<OrderGift> orderGifts = JSONArray.parseArray(s1, OrderGift.class);
            BigDecimal amount = orderGifts.stream().map(OrderGift::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            payOrder.setAmount(amount);
            payOrder.setPayType(dto.getPayType());
            payOrder.setBusinessType(dto.getBusinessType());
            payOrder.setBusinessId(dto.getParentOrderNo());
            payOrder.setUserId(dto.getUserId());
            payOrder.setSubject(dto.getUsername());
            payOrder.setPayStatus(0);
            payOrder.setUniPayOrderSn(dto.getUniPayOrderSn());
            super.insert(payOrder);
            return payOrder;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("支付创建失败!");
        } finally {
            lock.unlock();
        }
    }
}
